package edu.scut.course_management.filter;

import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * 登录认证拦截器 自定义登录认证拦截器的行为，让前端以 json 数据交互的方式与后端进行登录 替代 Spring Security 框架默认的表单登录行为
 * 实现前后端分离
 */
public class LoginAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        // 如果不是POST方法
        if (!request.getMethod().equals("POST")) {
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        // 如果不是 json 数据
        if(!request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            throw new AuthenticationServiceException("Content type not supported: " + request.getContentType());
        }
        // 处理 POST 方法的 json 格式登录数据
        String id = null, password = null;
        try {
            // 从请求体中读取账密
            Map<?, ?> map = new ObjectMapper().readValue(request.getInputStream(), Map.class);
            id = (String)map.get("id");
            password = (String)map.get("password");
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        id = id.trim();
        UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(id, password);
        setDetails(request, authRequest);
        return getAuthenticationManager().authenticate(authRequest);
    }
}
